package com.qianduo.servlet;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.qianduo.util.Constants;
import com.qianduo.vo.AccountForm;

import common.util.EncodeUtil;
import common.util.FileUtil;

public class UploadServlet extends HttpServlet {
	private String className = this.getClass().getName();
	private static final long serialVersionUID = -7301013037159270138L;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		this.doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)	throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		try {
			boolean isMultipart = ServletFileUpload.isMultipartContent(req);// 检查输入请求是否为multipart表单数据。
			if (isMultipart == true) {
				AccountForm account			= (AccountForm)req.getSession(false).getAttribute(Constants.ACCOUNT);				
				String tmpPath				= EncodeUtil.decodeUTF8(this.getClass().getClassLoader().getResource("").getPath())+"../../images/temp/"+account.getUsername();
				String imageUrl				= Constants.host+"images/temp/"+account.getUsername();
				FileItemFactory factory 	= new DiskFileItemFactory();// 为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。
				ServletFileUpload upload 	= new ServletFileUpload(factory);
				List<FileItem> items 		= upload.parseRequest(req);
				Iterator<FileItem> itr 		= items.iterator();
				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();					
					String fileName = item.getName();// 获得文件名，包括路径
					if (fileName != null) {						
						String fileType		= fileName.substring(fileName.lastIndexOf("."));
						String filePath		= tmpPath + fileType;
						FileUtil.createParentDir(filePath);
						File savedFile 		= new File(filePath);
						item.write(savedFile);
						out.print(imageUrl+fileType);
					}
				}
			} else {
				out.print("the enctype must be multipart/form-data");
			}
		} catch (Exception e) {
			Constants.log.error(className + " doPost", e);
		}
		out.flush();
		out.close();
	}

	public void oldFileUpload(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		// 定义上载文件的最大字节
		int MAX_SIZE = 102400 * 102400;
		// 创建根路径的保存变量
		String rootPath;
		// 声明文件读入类
		DataInputStream in = null;
		FileOutputStream fileOut = null;
		// 取得客户端的网络地址
		String remoteAddr = request.getRemoteAddr();
		// 获得服务器的名字
		String serverName = request.getServerName();

		// 取得互联网程序的绝对地址
		String realPath = request.getRealPath(serverName);
		realPath = realPath.substring(0, realPath.lastIndexOf("\\"));
		// 创建文件的保存目录
		rootPath = realPath + "\\upload\\";
		// 取得客户端上传的数据类型
		String contentType = request.getContentType();
		try {
			if (contentType.indexOf("multipart/form-data") >= 0) {
				// 读入上传的数据
				in = new DataInputStream(request.getInputStream());
				int formDataLength = request.getContentLength();
				if (formDataLength > MAX_SIZE) {
					String errormsg = ("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");
					request.setAttribute("errormsg", errormsg);
				}
				// 保存上传文件的数据
				byte dataBytes[] = new byte[formDataLength];
				int byteRead = 0;
				int totalBytesRead = 0;
				// 上传的数据保存在byte数组
				while (totalBytesRead < formDataLength) {
					byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
					totalBytesRead += byteRead;
				}
				// 根据byte数组创建字符串
				String file = new String(dataBytes);
				// out.println(file);
				// 取得上传的数据的文件名
				String saveFile = file.substring(file.indexOf("filename=\"") + 10);
				saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
				saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,
						saveFile.indexOf("\""));
				int lastIndex = contentType.lastIndexOf("=");
				// 取得数据的分隔字符串
				String boundary = contentType.substring(lastIndex + 1,
						contentType.length());
				// 创建保存路径的文件名
				String fileName = rootPath + saveFile;
				int pos;
				pos = file.indexOf("filename=\"");
				pos = file.indexOf("\n", pos) + 1;
				pos = file.indexOf("\n", pos) + 1;
				pos = file.indexOf("\n", pos) + 1;
				int boundaryLocation = file.indexOf(boundary, pos) - 4;
				// out.println(boundaryLocation);
				// 取得文件数据的开始的位置
				int startPos = ((file.substring(0, pos)).getBytes()).length;
				// out.println(startPos);
				// 取得文件数据的结束的位置
				int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
				// out.println(endPos);
				// 检查上载文件是否存在
				File checkFile = new File(fileName);
				if (checkFile.exists()) {
					Random r = new Random();
					r.nextInt();
					fileName = fileName.substring(0, fileName.length() - 4)
							+ r.nextInt()
							+ fileName.substring(fileName.length() - 4,
									fileName.length());
					// String errormsg="<p>" + saveFile + "文件已经存在.</p>";
					// request.setAttribute("errormsg", errormsg);
					// return "error.jsp";
					System.out.println("**********************" + fileName);
				}
				// 循环截取存放文件名
				// 检查上载文件的目录是否存在
				File fileDir = new File(rootPath);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 创建文件的写出类
				fileOut = new FileOutputStream(fileName);
				// 保存文件的数据
				fileOut.write(dataBytes, startPos, (endPos - startPos));
				fileOut.close();
				while (fileName.indexOf("\\") != -1) {
					fileName = fileName.substring(fileName.indexOf("\\") + 1);
				}
			} else {
				String content = request.getContentType();
				// out.println();
				String errormsg = "<p>上传的数据类型不是是multipart/form-data</p>";
				request.setAttribute("errormsg", errormsg);
			}
		} catch (Exception ex) {
			throw new ServletException(ex.getMessage());
		}
	}
}